﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using InstaMe.DB;
using InstaMe.Source.Model;
using InstaMe.Source.ViewModels;
using InstaMe.CustomControls;

namespace InstaMe.Source.Views
{
    public partial class DiaryPage : PhoneApplicationPage
    {
        private long mLastDiaryItemId = 0;
        private IDBListener mDBListener;
        private DiaryItemViewModel mDiaryItemViewModel;

        public DiaryPage()
        {
            InitializeComponent();
            mDiaryItemViewModel = new DiaryItemViewModel();
            mDBListener = new IDBListener();
            mDBListener.setDBCompleteDelegate(new DBCompleteDelegate(OnDBRequestComplete));
            mDiaryItemViewModel.CreateFakeData();
            MainListBox.DataContext = mDiaryItemViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                //GetDiaryItems(mLastDiaryItemId);
            }
        }

        private void GetDiaryItems(long aFromId)
        {
            DBManager.getInstance().LoadDiaryItemAsync(mDBListener, aFromId);
        }

        private void OnDBRequestComplete(QueryObject aQueryObj)
        {
            byte iQueryAction = aQueryObj.getAction();
            if (iQueryAction == QueryObject.DB_LOAD_DIARY_ITEM)
            {
                List<DiaryItem> mListDiaryItem = (List<DiaryItem>)aQueryObj.getParam(QueryObject.KEY_LIST_DIARY_ITEM_RETURN);
                if (mListDiaryItem != null && mListDiaryItem.Count > 0)
                {
                    mDiaryItemViewModel.LoadDiaryItems(mListDiaryItem, mLastDiaryItemId > 0);
                    mLastDiaryItemId = mListDiaryItem[mListDiaryItem.Count - 1].getId();
                }
            }
        }
    }
}